//
//  GroupListViewController.m
//  MapLink
//
//  Created by heng zhang on 21/05/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GroupListViewController.h"
#import "sqlite3.h"
#import "JSON.h"

// changes import viewscontrollers here
#import "GroupRegViewController.h"
#import "UserConfigViewController.h"
#import "UserGroupMapViewController.h"
#import "UIViewPassValueDelegate.h"
#import "AppConfig.h"
#import "GroupEntity.h"




@implementation GroupListViewController
@synthesize buffer;

- (id) init {
	[super initWithNibName:@"GroupListViewController" bundle:nil];
	[[self navigationItem] setTitle:@"My Groups"];
	return self;
}

- (IBAction) quitApp {
	// QUIT PROGRAM
	//[[UIApplication sharedApplication] terminate];
	exit(0);
}

- (void)viewDidLoad {
	[super viewDidLoad];
	groups = [[NSMutableArray alloc] init];
	
	//UIBarButtonItem *quitButton = [[UIBarButtonItem alloc] initWithTitle:@"Quit" style:UIBarButtonItemStylePlain target:self action:@selector(quitApp)];
//	self.navigationItem.leftBarButtonItem = quitButton;
//	[quitButton release];
	
	// meng
	// create appConfig object
	appConfig = [[AppConfig alloc] init];
	if ([appConfig firstTime]) {
		// this will call the user profile screen 1 sec later
		[ self performSelector:@selector(goProfile) withObject:nil afterDelay: 1.0f];	
	}
	else {
		// initialize variable
		displayName = [[NSString alloc] initWithString:[appConfig getProperty:@"user-name"]];
					   
	//	displayName = [appConfig getProperty:@"user-name"];
		
	}
	
	// create entity Manager Object
	//[EntityManager copyDatabaseIfNeeded];   // check and copy SQL.lite file to Documents folder for use
	//entityMgr = [[EntityManager alloc] init];	
	
	// Test codes for Entity
	//[EntityManager clearDatabase:entityMgr];
	//[EntityManager test:entityMgr];
	

	//displayName = [[NSString alloc] initWithString:@"YaoSheng"];
	deviceID = [[NSString alloc] 
				initWithString:[[UIDevice currentDevice] uniqueIdentifier]];
	groupName = [[NSString alloc] initWithString:@"team1"];
	
	[self loadGroupsFromDB];
	
	
}

- (void)viewWillAppear:(BOOL)animated {
	NSLog(@"Group List will appear");
	[super viewWillAppear:animated];
	[groupTableView reloadData];
	displayName = [[NSString alloc] 
				   initWithString:[appConfig getProperty:@"user-name"]];
	NSLog(@"Got display name: %@", displayName);
}

-(IBAction) goProfile {
	NSLog(@"goto UserConfig");
	// Check if I need to create the instance
	if (!userConfigViewController) {
		//userConfigViewController = [[UserConfigViewController alloc] init];
		userConfigViewController = [[UserConfigViewController alloc] initWithAppConfig:appConfig withDeviceID:deviceID];
		userConfigViewController.delegate = self;
	}
	
	userConfigViewController.displayName = displayName;
	//display a view modally
	[self presentModalViewController:userConfigViewController animated:YES];
}
-(IBAction) goJoin {
	NSLog(@"goto GroupReg");
	// Check if I need to create the instance
	if (!groupRegViewController) {
		groupRegViewController = [[GroupRegViewController alloc] init];
		groupRegViewController.delegate = self;
	}
	
	groupRegViewController.displayName = displayName;
	groupRegViewController.deviceID = deviceID;
	//display a view modally
	[self presentModalViewController:groupRegViewController animated:YES];
}



- (void)passValue:(NSString *)value forKey:(NSString *)key {
	NSLog(@"received: <%@=%@>", key, value);
	
	if([key isEqualToString:@"displayName"]) {// || [key isEqualToString:@"user-name"]){
		
		[displayName release];
		displayName = [[NSString alloc] initWithString:value];
		
		// meng code
		// save to app config file
		[appConfig setProperty:@"user-name" setValueTo:value];
		NSLog(@"user-name saved as %@", value);
		displayName = value;
	}
	
	if ([key isEqualToString:@"user-auth-code"]) {
		[appConfig setProperty:@"user-auth-code" setValueTo:value];
		NSLog(@"user-auth-code saved as %@", value);
		
	}
	
	
	if([key isEqualToString:@"groupName"]){
		if([self addGroupToDB:value]){
			[groupName release];
			groupName = [[NSString alloc] initWithString:value];
			[groups addObject:groupName];
			[groupTableView reloadData];
		}
	}
	if([key isEqualToString:@"unjoin"]){
		[self unjoinGroup:value];
	}
}




int dbGroupsCallback(void *context, int count, char **values, char **columns)
{
	NSLog(@"callback %d", count);
    NSMutableArray *groups = (NSMutableArray *)context;
    for (int i=0; i < count; i++) {
        const char *nameCString = values[i];
        [groups addObject:[NSString stringWithUTF8String:nameCString]];
    }
    return SQLITE_OK;
}

-(void) loadGroupsFromDB {
	NSFileManager *fileManager = [NSFileManager defaultManager];
	NSError *error;	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
	NSString *documentsDir = [paths objectAtIndex:0];
	NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"maplink.db"];
	BOOL existing = [fileManager fileExistsAtPath:dbPath]; 
	if(!existing) {
		NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"maplink.db"];
		if(! [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error])
			NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
	}
	
	[groups removeAllObjects];
	//NSString *file = [[NSBundle mainBundle] pathForResource:@"maplink" ofType:@"db"];

	sqlite3 *database = NULL;
	if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
		char * errmsg = NULL;
		int result = sqlite3_exec(database, "select name from groups", dbGroupsCallback, groups, &errmsg);
		if( result != SQLITE_OK) {
			NSLog(@"loadGroupsFromDB fail: %@", [NSString stringWithUTF8String:errmsg]);
		}
	}
	else {
		NSLog(@"error in opening database");
	}
	sqlite3_close(database);
}
-(BOOL) addGroupToDB:(NSString *)name {
	//NSString *file = [[NSBundle mainBundle] pathForResource:@"maplink" ofType:@"db"];
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
	NSString *documentsDir = [paths objectAtIndex:0];
	NSString *file = [documentsDir stringByAppendingPathComponent:@"maplink.db"];
	
	char * errmsg = NULL;
	sqlite3 *database = NULL;
	if(sqlite3_open([file UTF8String], &database) == SQLITE_OK) {
		NSString *strSql = [[NSString alloc] initWithFormat:@"insert into groups (name) values ('%@')", name];
		NSLog(@"sql is:%@", strSql);
		int result = sqlite3_exec( database, [strSql UTF8String], NULL, NULL, &errmsg );
		[strSql release];
		if( result != SQLITE_OK) {
			NSLog(@"error in adding group: %@", [NSString stringWithUTF8String:errmsg]);
			return NO;
		}
	}
	else {
		NSLog(@"error in opening database");
		return NO;
	}
	sqlite3_close(database);
	
	return YES;
}
-(BOOL) deleteGroupFromDB:(NSString *)name {
	//NSString *file = [[NSBundle mainBundle] pathForResource:@"maplink" ofType:@"db"];
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
	NSString *documentsDir = [paths objectAtIndex:0];
	NSString *file = [documentsDir stringByAppendingPathComponent:@"maplink.db"];
	
	char * errmsg = NULL;
	sqlite3 *database = NULL;
	if(sqlite3_open([file UTF8String], &database) == SQLITE_OK) {
		NSString *strSql = [[NSString alloc] initWithFormat:@"delete from groups where name='%@'", name];
		NSLog(@"sql is:%@", strSql);
		int result = sqlite3_exec( database, [strSql UTF8String], NULL, NULL, &errmsg );
		[strSql release];
		if( result != SQLITE_OK) {
			NSLog(@"error in deleting group: %@", [NSString stringWithUTF8String:errmsg]);
			return NO;
		}
	}
	else {
		NSLog(@"error in opening database");
		return NO;
	}
	sqlite3_close(database);
	
	return YES;
}

-(void) unjoinGroup:(NSString *)name {
	NSURL *url = [NSURL URLWithString:[NSString 
									   stringWithFormat:@"http://mybuddies.emiu.net/group.php?action=unjoin&device_id=%@&name=%@&group=%@",
									   [deviceID stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], 
									   [displayName stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], 
									   [name stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]];
	if(url == NULL) {
		UIAlertView *alertView = [[UIAlertView alloc] 
								  initWithTitle:@"Error" 
								  message:@"Invalid URL.\nPlease remove SPACE or any other invalid charactors." 
								  delegate:nil 
								  cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
		[alertView release];
	}
	NSLog(@"url is: %@", url);
	[activityIndicatorView startAnimating];
	NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
	[req setHTTPMethod:@"GET"];
	
	conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
	if (conn) {
		self.buffer = [NSMutableData data];
	}
}

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
	[buffer setLength:0];
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data {
	[buffer appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
	[buffer release];
	[connection release];
	[activityIndicatorView stopAnimating];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
	NSLog(@"Done with bytes %d", [buffer length]);
	NSMutableString *jsonString = [[NSMutableString alloc] initWithBytes:[buffer mutableBytes]
																  length:[buffer length]
																encoding:NSUTF8StringEncoding];
	NSLog(@"result is %@", jsonString);
	NSDictionary *response = [jsonString JSONValue];
	NSString *result = [response objectForKey:@"result"];
	if([result isEqualToString:@"Y"]){
		//success
		if ([self deleteGroupFromDB:[response objectForKey:@"group"]]) {
			[self loadGroupsFromDB];
			[groupTableView reloadData];
		};
	}else{
		//fail
		UIAlertView *alertView = [[UIAlertView alloc] 
								  initWithTitle:@"Error" 
								  message:[response objectForKey:@"message"] 
								  delegate:nil 
								  cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alertView show];
		[alertView release];
	}
	
	[jsonString release];
	[connection release];
	[activityIndicatorView stopAnimating];
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	return [groups count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    [[cell textLabel] setText:[groups objectAtIndex:[indexPath row]]];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
	
    return cell;
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source.
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	// Check if I need to create the instance
	if (!mapViewController) {
		mapViewController = [[UserGroupMapViewController alloc] init];
		mapViewController.delegate = self;
	}
	[groupName release];
	groupName = [[NSString alloc] initWithString:[groups objectAtIndex:[indexPath row]]];
	mapViewController.groupName=groupName;
	mapViewController.displayName=displayName;
	mapViewController.deviceID=deviceID;
	
	// Push it onto the top of the navigation controller's stack
	[[self navigationController] pushViewController:mapViewController 
										   animated:YES];
}


/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations.
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
}


- (void)dealloc {
	[buffer release];
	[displayName release];
	[deviceID release];
	[groupName release];
	[userConfigViewController release];
	[groupRegViewController release];
	[mapViewController release];
	[groups release];
	
	// meng
	[appConfig release];
	
    [super dealloc];
}


@end
